﻿/* **************************************************************************
 *
 * Copyright 2007-2010 Jeff Hardy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * *************************************************************************/

using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using IronPython.Runtime;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Hosting.Providers;

namespace NWSGI
{
    internal delegate WsgiFileWrapper CreateFileWrapper(PythonFile file, [DefaultParameterValue(0)]int block_size);

    /// <summary>
    /// Used to wrap a Python file-like object to implement wsgi.file_wrapper (see PEP 333 for details).
    /// </summary>
    internal class WsgiFileWrapper : IEnumerable
    {
        private PythonFile file;
        private ScriptEngine engine;
        private int block_size;

        public WsgiFileWrapper(ScriptEngine engine, PythonFile file, int block_size)
        {
            this.file = file;
            this.engine = engine;
            this.block_size = block_size > 0 ? block_size : 4096;
        }

        private string fullPath;
        public string FullPath
        {
            get
            {
                if(fullPath == null)
                {
                    ModuleContext context = new ModuleContext(new PythonDictionary(), (PythonContext)HostingHelpers.GetLanguageContext(engine));
                    fullPath = IronPython.Modules.PythonNT._getfullpathname(context.GlobalContext, file.name);
                }

                return fullPath;
            }
        }

        public void close()
        {
            file.close();
        }

        public IEnumerator GetEnumerator()
        {
            FileStream fs = new FileStream(FullPath, FileMode.Open, FileAccess.Read);

            byte[] data = new byte[this.block_size];
            int count;
            while((count = fs.Read(data, 0, block_size)) > 0)
            {
                yield return Wsgi.Latin1.GetString(data, 0, count);
            }
        }
    }
}
